package api

import (
	"gitee.com/ling1314/origin-utility/constant"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/service"
	"gitee.com/ling1314/origin-utility/utils"
	"github.com/gin-gonic/gin"
)

type appApi struct{}

func (a appApi) DeleteIssueApp(c *gin.Context) {
	input := struct {
		Id int64 `form:"id"`
	}{}
	if err := c.ShouldBindQuery(&input); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	if err := service.APPService.DeleteIssueApp(input.Id); err != nil {
		BadWithError(c, err)
		return
	}
	Ok204(c)
}

func (a appApi) GetIssueList(c *gin.Context) {
	input := struct {
		Name string `form:"name"`
	}{}
	if err := c.ShouldBindQuery(&input); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	rs, err := service.APPService.GetIssueList(input.Name)
	if err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, rs)
}

func (a appApi) GetAppInstallList(c *gin.Context) {
	p := struct {
		Id int64 `uri:"id,string"`
	}{}
	if err := c.ShouldBindUri(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	var (
		err error
		li  []model.AppInstall
	)
	if li, err = service.APPService.GetAppInstallList(p.Id); err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, li)
}

func (a appApi) CheckIssueStatus(c *gin.Context) {
	p := struct {
		ClusterId int64                  `json:"clusterId,string"`
		AppIds    utils.StringArrayInt64 `json:"appIds"`
	}{}
	if err := c.ShouldBindJSON(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	var (
		err error
		li  []model.AppInstall
	)
	if li, err = service.APPService.CheckIssueStatus(p.AppIds, p.ClusterId); err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, li)
}

func (a appApi) IssueApp(c *gin.Context) {
	var p model.IssueAppForm
	if err := c.ShouldBindJSON(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	if err := service.APPService.IssueApp(p); err != nil {
		BadWithError(c, err)
		return
	}
	Ok204(c)
}

func (a appApi) GetSelfAppList(c *gin.Context) {
	self := GetCurrentUser(c)
	li, err := service.APPService.GetSelfAppList(self)
	if err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, li)
}

func (a appApi) GetAppIssueInfo(c *gin.Context) {
	p := struct {
		Id int64 `uri:"id,string"`
	}{}
	if err := c.ShouldBindUri(&p); err != nil {
		BadWithCode(c, constant.ParamsError)
		return
	}
	var (
		err error
		m   model.AppIssue
	)
	if m, err = service.APPService.GetAppIssueInfo(p.Id); err != nil {
		BadWithError(c, err)
		return
	}
	Ok(c, m)
}
